import { withRouter } from "next/router";
import { request } from "../lib/api";

const PER_PAGE = 20;

const Search = ({ router, repos }) => {
  return (
    <div className="root">
      <style jsx>
        {`
          :global(.ant-list-item.selected) {
            border-left: 2px solid #e36209;
            font-weight: 100;
          }

          .root {
            padding: 20px 0;
          }

          .list-header {
            font-weight: 800;
            font-size: 16px;
          }

          .repos-title {
            border-bottom: 1px solid #eee;
            font-size: 24px;
            line-height: 50px;
          }

          .pagination {
            margin-top: 16px;
            text-align: right;
          }
        `}
      </style>
    </div>
  );
};

Search.getInitialProps = async ({ ctx }) => {
  const { query, sort, lang, order = "desc", page } = ctx.query;

  if (!query) {
    return {
      repos: {
        total_count: 0,
      },
    };
  }

  let queryString = `?q=${query}`;

  if (lang) {
    queryString += `+language:${lang}`;
  }

  if (sort) {
    queryString += `&sort=${sort}&order=${order}`;
  }

  if (page) {
    queryString += `&page=${page}`;
  }

  queryString += `&per_page=${PER_PAGE}`;

  const result = await request(
    {
      url: `/search/repositories${queryString}`,
    },
    ctx.req,
    ctx.res
  );

  return {
    repos: result.data,
  };
};

export default withRouter(Search);
